//
//  DHOrderDetail_CheckViewController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/26.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHOrderDetail_CheckViewController.h"
#import "DHOrderDetailAddressCell.h"
#import "DHOrderDetailLeaseCell.h"
#import "DHOrderDetail_SixCell.h"
#import "Address.h"
#import "DHOrderPayViewController.h"
#import "DHOrderManagerViewController.h"

@interface DHOrderDetail_CheckViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (assign, nonatomic) BOOL isSix; //是否是6小时送达城市
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;

@property (strong, nonatomic) Address *address;
@property (weak, nonatomic) IBOutlet DHGradualButton *payButton;

@property (strong, nonatomic) NSDictionary *orderDic;

@end

@implementation DHOrderDetail_CheckViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"订单详情";
    
    self.bottomView.layer.cornerRadius = 2;
    self.bottomView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.bottomView.layer.shadowRadius = 5;
    self.bottomView.layer.shadowOpacity = 0.5;
    self.bottomView.layer.shadowOffset  = CGSizeMake(0, 0);
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetailAddressCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetailAddressCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetailLeaseCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetailLeaseCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHOrderDetail_SixCell" bundle:nil] forCellReuseIdentifier:kDHOrderDetail_SixCell];
    
    [[DHNetAPIClient shareDHNetAPIClient] request_orders_detailWithParams:@{@"order_id":self.orderID} andBlock:^(id data, NSError *error) {
        self.orderDic = [data objectForKey:@"order"];
        [self updateData];
    }];
}

- (void)backAction{
    UIViewController *orderManagerVC;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[DHOrderManagerViewController class]]) {
            orderManagerVC = vc;
        }
    }
    if (orderManagerVC) {
        [self.navigationController popToViewController:orderManagerVC animated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (void)updateData{
    self.address = [Address modelWithDictionary:[self.orderDic objectForKey:@"consignee"]];
    
    // 计算订单支付金额
    NSArray *costsArr = [self.orderDic objectForKey:@"costs"];
    if (costsArr) {
        __block CGFloat payPrice = 0;
        [costsArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGFloat cost_value = [[obj objectForKey:@"cost_value"] floatValue];
            if (cost_value >= 0) {
                payPrice += cost_value;
            }else{
                payPrice -= cost_value;
            }
        }];
        self.totalPriceLabel.text = [NSString stringWithFormat:@"总额：￥%.2f",payPrice];
    }
    
    if ([[self.orderDic objectForKey:@"status"] integerValue] == OrderStateUnpaid) {
        self.payButton.hidden = NO;
    }else{
        self.payButton.hidden = YES;
    }
    
    WeakSelf(weakSelf)
    [self.payButton bk_addEventHandler:^(id sender) {
        NSArray *contentProductArr = [weakSelf.orderDic objectForKey:@"content"];
        NSMutableArray *productIDArr = [NSMutableArray array];
        [contentProductArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *size = [[obj objectForKey:@"sizes"] objectAtIndex:0];;
            [productIDArr addObject:@{@"_id":size[@"_id"]}];
        }];
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@{@"leased":productIDArr} forKey:@"products"];
        if ([weakSelf.orderDic objectForKey:@"consignee"]) {
            [params setObject:[weakSelf.orderDic objectForKey:@"consignee"] forKey:@"consignee"];
        }
        DHOrderPayViewController *orderPayController = [[DHOrderPayViewController alloc] initWithOrders:@[weakSelf.orderDic] orderValidParams:params];
        [weakSelf.navigationController pushViewController:orderPayController animated:YES];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma UITableViewDelegate and UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isSix) {
        return 3;
    }else{
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 82;
    }else if (indexPath.section == 2){
        return 100;
    }else{
        return 80 + [[self.orderDic objectForKey:@"content"] count] * 30;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DHOrderDetailAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetailAddressCell forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.phoneLabel.text = self.address.phone;
        cell.nameLabel.text = self.address.name;
        cell.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",self.address.province? :@"",self.address.city? :@"",self.address.district? :@"",self.address.address? :@""];
        cell.arrowImgView.hidden = YES;
        return cell;
    }else if (indexPath.section == 2){
        DHOrderDetail_SixCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetail_SixCell forIndexPath:indexPath];
        [cell.express_switch bk_addEventHandler:^(UISwitch *sender) {
            NSLog(@"选择");
//            if (sender.on) {
//                self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.totalPrice + 100];
//            }else{
//                self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",self.totalPrice];
//            }
            
        } forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        DHOrderDetailLeaseCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHOrderDetailLeaseCell forIndexPath:indexPath];
        [cell updateCellWithProduct:[self.orderDic objectForKey:@"content"] costDic:[self.orderDic objectForKey:@"costs"]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.1;
    }else{
        return 46;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 46)];
        headerView.backgroundColor = [UIColor whiteColor];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, headerView.width - 14, headerView.height)];
        titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14];
        titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        titleLabel.text = @"订阅";
        [headerView addSubview:titleLabel];
        return headerView;
    }else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

@end
